<template>
  <div class="fullscreen-container">
    <common-header page-title="政策详情" />

    <div class="detail-container">
      <back-button />
      <div class="policy-card">
        <div class="title-section">
          <h1 class="policy-title">{{ policy.title }}</h1>
          <div class="meta-info">
            <div class="meta-item">
              <span class="meta-label">来源:</span>
              <span class="meta-value">{{ policy.source }}</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">发布时间:</span>
              <span class="meta-value">{{ formatDate(policy.publishTime) }}</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">浏览次数:</span>
              <span class="meta-value">{{ policy.viewCount }}</span>
            </div>
          </div>
        </div>

        <div class="policy-content">
          <p class="content-text">{{ policy.content }}</p>
        </div>

        <div v-if="policy.video" class="policy-video">
          <video :src="policy.video" controls class="video-player">
            您的浏览器不支持视频播放。
          </video>
        </div>

        <div class="action-section">
          <button v-if="policy.attachment" @click="handleDownload" class="download-btn">
            <i class="icon-download"></i> 下载附件
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import request from '@/utils/request'
import CommonHeader from '@/views/user/support/components/CommonHeader.vue'
import BackButton from '@/views/user/support/components/BackButton.vue'
import axios from 'axios'

const route = useRoute()
const policyId = route.params.id
const policy = ref({})

const handleDownload = async () => {
  try {
    const url = `${BASE_URL}/api/v1/government/public/download/attachment/${policy.value.id}`;
    const response = await axios.get(url, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      },
      responseType: 'blob'
    });

    const blob = new Blob([response.data]);
    const downloadUrl = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = downloadUrl;
    a.download = policy.value.attachment.split('/').pop();
    document.body.appendChild(a);
    a.click();
    a.remove();
    window.URL.revokeObjectURL(downloadUrl);
  } catch (error) {
    console.error('下载失败:', error);
    alert('下载失败，请重试');
  }
};

const fetchPolicy = async () => {
  try {
    const res = await request.get(BASE_URL+`/api/v1/government/public/policy/${policyId}`)
    policy.value = res.data[0];
  } catch (err) {
    console.error('获取政策失败:', err)
  }
}

const incrementViewCount = async () => {
  try {
    await request.post(BASE_URL + `/api/v1/government/public/increment-view-count?policyId=${policyId}`)
    policy.value.viewCount += 1
  } catch (err) {
    console.error('增加浏览次数失败:', err)
  }
}

let pollInterval = null

const startPolling = () => {
  fetchPolicy()
  pollInterval = setInterval(() => {
    fetchPolicy()
  }, 1000)
}

const stopPolling = () => {
  if (pollInterval) {
    clearInterval(pollInterval)
    pollInterval = null
  }
}

onMounted(async () => {
  await fetchPolicy()
  await incrementViewCount()
  startPolling()
})

onUnmounted(() => {
  stopPolling()
})

const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = (d.getMonth() + 1).toString().padStart(2, '0')
  const day = d.getDate().toString().padStart(2, '0')
  return `${year}-${month}-${day}`
}
</script>

<style scoped>
.fullscreen-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f8f9fa;
}

.detail-container {
  flex: 1;
  padding: 24px;
  width: 100%;
  max-width: 960px;
  margin: 0 auto;
}

.policy-card {
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  padding: 40px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.policy-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
}

.title-section {
  margin-bottom: 32px;
  border-bottom: 1px solid #f0f2f5;
  padding-bottom: 24px;
}

.policy-title {
  font-size: 28px;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 20px;
  line-height: 1.4;
}

.meta-info {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
}

.meta-item {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.meta-label {
  font-weight: 500;
  color: #666;
  margin-right: 8px;
}

.meta-value {
  color: #333;
  font-weight: 400;
}

.policy-content {
  margin-bottom: 32px;
}

.content-text {
  font-size: 16px;
  line-height: 1.8;
  color: #333;
  white-space: pre-wrap;
  font-weight: 400;
}

.policy-video {
  margin: 32px 0;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.video-player {
  width: 100%;
  height: auto;
  display: block;
}

.action-section {
  display: flex;
  justify-content: flex-end;
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #f0f2f5;
}

.download-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 10px 20px;
  background: linear-gradient(135deg, #4e7af9, #6a5acd);
  color: white;
  border-radius: 6px;
  border: none;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(78, 122, 249, 0.3);
}

.download-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(78, 122, 249, 0.4);
  background: linear-gradient(135deg, #6a5acd, #4e7af9);
}

.download-btn i {
  margin-right: 8px;
  font-size: 16px;
}

@media (max-width: 768px) {
  .detail-container {
    padding: 16px;
  }

  .policy-card {
    padding: 24px;
  }

  .policy-title {
    font-size: 22px;
  }

  .meta-info {
    flex-direction: column;
    gap: 12px;
  }

  .meta-item {
    font-size: 13px;
  }

  .action-section {
    justify-content: flex-start;
  }
}

@media (max-width: 480px) {
  .policy-card {
    padding: 20px;
  }

  .policy-title {
    font-size: 20px;
  }

  .content-text {
    font-size: 15px;
  }
}
</style>